import { useState, useEffect } from 'react'
import { useDrop } from 'react-dnd'
import { ItemTypes } from './ItemTypes'
import { Button, Checkbox } from 'antd'

const style = {
  height: '100%'
}

const DropContainer = () => {
  const [type, setType] = useState('')
  const [arr, setArr] = useState([])
  const [id, setId] = useState(0)
  const [{ canDrop, isOver }, drop] = useDrop(() => ({
    accept: ItemTypes.BOX,
    drop: (item) => {
      setType(item.type)
      setId(id => id + 1)
    },
    collect: (monitor) => ({
      isOver: monitor.isOver(),
      canDrop: monitor.canDrop(),
    }),
  }))
  const isActive = canDrop && isOver
  let backgroundColor = '#f6f7f8'
  if (isActive) {
    backgroundColor = '#999'
  }
  else if (canDrop) {
    backgroundColor = '#999'
  }
  useEffect(() => {
    // 根据type渲染不同组件
    if (type === 'Button') arr.push({
      ele: (key) => <div key={key}><Button type='primary'>按钮</Button></div>,
    })
    if (type === 'Checkbox') arr.push({
      ele: (key) => <div key={key}><Checkbox>多选框</Checkbox></div>,
    })
    setArr(arr => [...arr])
  }, [id])

  return (
    <div ref={drop} style={{ ...style, backgroundColor }}>
      {isActive ? 'Release to drop' : 'Drag a box here'} {id}<br /><br />
      {
        arr.map((item, key) => {
          return item.ele(key)
        })
      }
    </div>
  )
}
export default DropContainer